<template>
  <div>
    <div>
      <we-button v-if="baseCode" @click="dialogFormVisible = true" type="primary" size="mini">
        <em class="el-icon-plus"></em> 新增
      </we-button>
      <we-button v-if="baseCode" @click="detailRow(currentRow)" type="primary" size="mini">
        <em class="el-icon-edit"></em> 修改
      </we-button>
      <we-button v-if="baseCode" @click="deleteRow"  type="primary" size="mini">
        <em class="el-icon-delete"></em> 删除
      </we-button>
      <span v-if="baseName">当前人员：【 {{baseName}} 】</span>
    </div>

    <!-- 表格 -->
    <el-table
      size="mini"
      :header-cell-style="rowClass"
      :data="tableData"
      height="116px"
      border
      highlight-current-row
      resizable
      ref="singleTable"
      @row-dblclick="detailRow"
      @current-change="handleCurrentChange"
      style="width: 100%; margin-top: 5px"
    >
      <el-table-column type="index" label="#"> </el-table-column>
      <el-table-column
        prop="startTime"
        :show-overflow-tooltip="true"
        width="150"
        label="学习起始日期"
      >
      </el-table-column>
      <el-table-column
        prop="endTime"
        :show-overflow-tooltip="true"
        width="150"
        label="学习终止日期"
      >
      </el-table-column>
      <el-table-column
        prop="traniningCategory_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="培训类别"
      >
      </el-table-column>
      <el-table-column
        prop="traningDays"
        :show-overflow-tooltip="true"
        width="150"
        label="培训天数"
      >
      </el-table-column>
      <el-table-column
        prop="totalClassHours"
        :show-overflow-tooltip="true"
        width="150"
        label="总学时"
      >
      </el-table-column>
      <el-table-column
        prop="traniningCourseName"
        :show-overflow-tooltip="true"
        width="150"
        label="培训班名称"
      >
      </el-table-column>
      <el-table-column
        prop="learningContent"
        :show-overflow-tooltip="true"
        width="150"
        label="学习内容"
      >
      </el-table-column>
      <el-table-column
        prop="educationTraningNature_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="教育培训性质"
      >
      </el-table-column>
      <el-table-column
        prop="learningStyle_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="学习方式"
      >
      </el-table-column>
      <el-table-column
        prop="academicRecord"
        :show-overflow-tooltip="true"
        width="150"
        label="学习成绩"
      >
      </el-table-column>
      <el-table-column
        prop="educationTraningResults_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="教育培训结果"
      >
      </el-table-column>
      <el-table-column
        prop="traningFrom_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="培训形式"
      >
      </el-table-column>
      <el-table-column
        prop="organizerCategory_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="主办单位类别"
      >
      </el-table-column>
      <el-table-column
        prop="organizer"
        :show-overflow-tooltip="true"
        width="150"
        label="主办单位"
      >
      </el-table-column>
      <el-table-column
        prop="sponsorNature_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="主办单位性质"
      >
      </el-table-column>
      <el-table-column
        prop="undertaker"
        :show-overflow-tooltip="true"
        width="150"
        label="承办单位"
      >
      </el-table-column>
      <el-table-column
        prop="investmentAmont"
        :show-overflow-tooltip="true"
        width="150"
        label="投入金额"
      >
      </el-table-column>
      <el-table-column
        prop="traniningChannels_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="培训渠道"
      >
      </el-table-column>
      <!-- <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <we-button @click="detailRow(scope.row)" type="primary" size="mini"
            >详情</we-button
          >
          <we-button type="danger" @click="deleteRow(scope.row)" size="mini">删除</we-button>
        </template>
      </el-table-column> -->
    </el-table>
    <div class="table_tools">
      <we-pagination
        :total="pagination.total"
        :page="pagination.pageNum"
        :pageSize="pagination.pageSize"
        @currentChange="currentChange($event)"></we-pagination>
    </div>
    <!-- 表格 -->

    <!-- 新增弹窗 -->
    <el-dialog
      title="教育培训子集"
      :visible.sync="dialogFormVisible"
      @close="handleOffDialog"
      append-to-body
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="140px"
        size="mini"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学习起始日期" prop="startTime">
              <el-date-picker
                class="inputW"
                v-model="ruleForm.startTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学习终止日期" prop="endTime">
              <el-date-picker
                class="inputW"
                v-model="ruleForm.endTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="培训类别" prop="traniningCategory">
              <el-select
                class="inputW"
                v-model="ruleForm.traniningCategory"
                placeholder="请选择"
                clearable
              >
                <el-option v-for="item in traniningCategory" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训天数" prop="traningDays">
              <el-input
                class="inputW"
                v-model="ruleForm.traningDays"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总学时" prop="totalClassHours">
              <el-input
                class="inputW"
                v-model="ruleForm.totalClassHours"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训班名称" prop="traniningCourseName">
              <el-input
                class="inputW"
                v-model="ruleForm.traniningCourseName"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学习内容" prop="learningContent">
              <el-input
                class="inputW"
                v-model="ruleForm.learningContent"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教育培训性质" prop="educationTraningNature">
              <el-select
                class="inputW"
                v-model="ruleForm.educationTraningNature"
                placeholder="请选择"
                clearable
              >
                <el-option v-for="item in educationTraningNature" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学习方式" prop="learningStyle">
              <el-select
                class="inputW"
                v-model="ruleForm.learningStyle"
                placeholder="请选择"
                clearable
              >
                <el-option v-for="item in learningStyle" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学习成绩" prop="academicRecord">
              <el-input
                class="inputW"
                v-model="ruleForm.academicRecord"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="教育培训结果" prop="educationTraningResults">
              <el-select
                class="inputW"
                v-model="ruleForm.educationTraningResults"
                placeholder="请选择"
                clearable
              >
                <el-option v-for="item in educationTraningResults" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训形式" prop="traningFrom">
              <el-select
                class="inputW"
                v-model="ruleForm.traningFrom"
                placeholder="请选择"
                clearable
                multiple
              >
                <el-option v-for="item in traningFrom" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="主办单位类别" prop="organizerCategory">
              <el-select
                class="inputW"
                v-model="ruleForm.organizerCategory"
                placeholder="请选择"
                clearable
              >
                <el-option v-for="item in organizerCategory" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主办单位" prop="organizer">
              <el-input
                class="inputW"
                v-model="ruleForm.organizer"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="主办单位性质" prop="sponsorNature">
              <el-select
                class="inputW"
                v-model="ruleForm.sponsorNature"
                placeholder="请选择"
                clearable
              >
                <el-option v-for="item in sponsorNature" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="承办单位" prop="undertaker">
              <el-input
                class="inputW"
                v-model="ruleForm.undertaker"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="投入金额" prop="investmentAmont">
              <el-input
                class="inputW"
                v-model="ruleForm.investmentAmont"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训渠道" prop="traniningChannels">
              <el-select
                class="inputW"
                v-model="ruleForm.traniningChannels"
                placeholder="请选择"
                clearable
              >
                <el-option v-for="item in traniningChannels" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <we-button size="mini" @click="handleOffDialog"
          >取 消</we-button
        >
        <we-button v-if="!isUpdate" size="mini" type="primary" @click="submitForm('ruleForm')"
          >新 增</we-button
        >
        <we-button v-if="isUpdate" size="mini" type="primary" @click="updateForm('ruleForm')"
          >修 改</we-button
        >
      </div>
    </el-dialog>
    <!-- 新增弹窗 -->
  </div>
</template>

<script>
import WeButton from '@/components/WeButton'
import WePagination from '@/components/WePagination'
import { getAction, postAction, deleteAction, putAction } from '@/api/manage'
import {bus} from "@/utils/eventBus";
import {educationTranining, opDictNew} from "@/api/apiUrl";
export default {
  components: {
    WeButton,
    WePagination
  },
  data () {
    return {
      isUpdate: false,
      pagination: {
        total: 10, // 总数据条数
        pageSize: 10, // 每页条数
        pageNum: 1 // 当前页
      }, // 列表分页数据
      tableData: [],
      dialogFormVisible: false,
      currentRow: null,
      ruleForm: {
        startTime: '',
        endTime: '',
        traniningCategory: '',
        traningDays: '',
        totalClassHours: '',
        traniningCourseName: '',
        learningContent: '',
        educationTraningNature: '',
        learningStyle: '',
        academicRecord: '',
        educationTraningResults: '',
        traningFrom: [],
        organizerCategory: '',
        organizer: '',
        sponsorNature: '',
        undertaker: '',
        investmentAmont: '',
        traniningChannels: '',
        uuidList:[],
      },
      rules: {
        startTime: [
          { required: true, message: '请选择学习起始日期', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择学习终止日期', trigger: 'change' }
        ],
        traniningCategory: [{ required: true, message: '请选择培训类别', trigger: 'blur' }],
        traningDays: [
          { required: true, message: '请填写培训天数', trigger: 'blur' },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入数字(可保留两位小数)'
          }
        ],
        totalClassHours: [
          { required: true, message: '请填写总学时', trigger: 'blur' },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入数字(可保留两位小数)'
          }
        ],
        traniningCourseName: [
          { required: true, message: '请填写培训班名称', trigger: 'blur' }
        ],
        academicRecord: [
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入数字(可保留两位小数)'
          }
        ],
        traningFrom: [
          { required: true, message: '请选择培训形式', trigger: 'change' }
        ],
        organizer: [
          { required: true, message: '请填写主办单位', trigger: 'blur' }
        ],
        investmentAmont: [
          { required: true, message: '请填写投入金额', trigger: 'blur' },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入数字(可保留两位小数)'
          }
        ],
        traniningChannels: [
          { required: true, message: '请选择培训渠道', trigger: 'change' }
        ]
      },

      traniningCategory: [],
      educationTraningNature: [],
      learningStyle: [],
      educationTraningResults: [],
      traningFrom: [],
      organizerCategory: [],
      sponsorNature: [],
      traniningChannels: [],
      baseCode: '',
      baseName: '',
    }
  },
  watch: {
    dialogFormVisible () {
      if (this.dialogFormVisible === false) {
        if (this.isUpdate) {
          setTimeout(() => {
            this.isUpdate = false
            this.clearForm()
            if (this.$refs.ruleForm !== undefined) {
              this.$refs.ruleForm.resetFields()
            }
          }, 500)
        }
        if (this.$store.state.education === true) {
          this.$store.commit('changeEducation', false)
        }
      }
    },
    '$store.state.baseCode'(newval) {
      this.baseCode  = newval
      this.getList ()
    },
    '$store.state.baseName'(newval) {
      this.baseName  = newval
    },
    '$store.state.education' (newval) {
      if (newval === true) {
        this.dialogFormVisible = true
        if (this.$store.state.updateSubset === true) {
          this.isUpdate = true
        } else {
          this.isUpdate = false
        }
        this.$store.commit('changeUpdateSubset', false)
        this.baseCodes = this.$store.state.baseCodes
        this.getTraniningCategory()
        this.getEducationTraning()
        this.getLearningStyle()
        this.getEducationTraningResults()
        this.getTrainingFrom()
        this.getOrganizerCategory()
        this.getSponsorNature()
        this.getTraniningChannels()
      }
    }
  },
  methods: {
    clickSubset () {
      this.baseCode = this.$store.state.baseCode
      this.getList()
      this.getTraniningCategory()
      this.getEducationTraning()
      this.getLearningStyle()
      this.getEducationTraningResults()
      this.getTrainingFrom()
      this.getOrganizerCategory()
      this.getSponsorNature()
      this.getTraniningChannels()
    },
    batchAdd(data){
      this.dialogFormVisible = true
      this.ruleForm.uuidList = data
    },
    /*
     * 新增
     */
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.ruleForm))
          data.traningFrom = data.traningFrom.join(',')
          data.baseCode = this.baseCode
          data.sysOrgCode = '测试部门'
          data.createUser = '测试员'
          if (this.$store.state.education === true) {
            for (let i = 0; i < this.baseCodes.length; i++) {
              data.baseCode = this.baseCodes[i]
              postAction(educationTranining.add, data)
                .then(result => {
                  if (result.code === 200) {
                    this.dialogFormVisible = false
                    bus.$emit('handleDialog')
                    this.$message({
                      type: 'success',
                      message: '新增成功!'
                    })
                    this.clearForm()
                  } else {
                    this.$message({
                      type: 'waring',
                      message: result.msg
                    })
                  }
                })
            }
          } else {
            postAction(educationTranining.add, data)
              .then(result => {
                if (result.code === 200) {
                  this.dialogFormVisible = false
                  bus.$emit('handleDialog')
                  this.getList()
                  this.$message({
                    type: 'success',
                    message: '新增成功!'
                  })
                } else {
                  this.$message({
                    type: 'waring',
                    message: result.msg
                  })
                }
              })
          }
        } else {
          return false
        }
      })
    },
    handleCurrentChange(val) {
        this.currentRow = val;
    },
    /**
     * 删除
     */
    deleteRow (row) {
      if(!this.currentRow){
        this.$message("请选择要删除的数据！")
        return
      }
      this.$confirm('是否要删除这条数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          postAction(educationTranining.delete, { uuids: [this.currentRow.uuid] })
            .then((res) => {
              if (res.code === 200) {
                this.getList()
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
              } else {
                this.$message({
                  type: 'waring',
                  message: res.msg
                })
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    /**
     * 修改
     */
    updateForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.ruleForm))
          data.traningFrom = data.traningFrom.join(',')
          data.updateUser = '修改员'
          postAction(educationTranining.update, data)
            .then(result => {
              if (result.code === 200) {
                this.dialogFormVisible = false
                bus.$emit('handleDialog')
                this.getList()
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
              } else {
                this.$message({
                  type: 'waring',
                  message: result.msg
                })
              }
            })
        } else {
          return false
        }
      })
    },
    handleOffDialog() {
      this.dialogFormVisible = false
      bus.$emit('handleDialog')
    },
    /**
     * 查询
     */
    getList () {
      let self = this
      postAction(educationTranining.educationTraniningSearch, { baseCode: this.baseCode,size:this.pagination.pageSize, page:this.pagination.pageNum })
        .then((res) => {
          if (res.code === 200) {
            if (!res.data.list.length && self.pagination.pageNum !== 1) {
              self.pagination.pageNum -= 1
              self.getList()
              return
            }
            if (self.pagination.pageNum === 1 && res.data.list.length === 0) {
              self.pagination.total = 0
            } else {
              self.pagination.total = res.data.total
            }
            res.data.list.map(v => { v.traningFrom = v.traningFrom.split(',') })
            self.tableData = res.data.list
          }
        })
    },

    /*
     * 获取培训类别字典
     */
    async getTraniningCategory () {
      const result = await getAction(`${opDictNew.findByType}?type=rs_spxlb`)
      this.traniningCategory = result.data
      // const result = await getAction('opDictItem/getDictItemListByCode', {
      //   code: 'tranining_category'
      // })
      // this.traniningCategory = result.data.list
    },

    /*
     * 获取教育培训性质字典
     */
    async getEducationTraning () {
      const result = await getAction(`${opDictNew.findByType}?type=rs_ce`)
      this.educationTraningNature = result.data
    },

    /*
     * 获取学习方式字典
     */
    async getLearningStyle () {
      const result = await getAction(`${opDictNew.findByType}?type=rs_bm`)
      this.learningStyle = result.data
    },

    /*
     * 获取学习方式字典
     */
    async getEducationTraningResults () {
      const result = await getAction(`${opDictNew.findByType}?type=rs_hy`)
      this.educationTraningResults = result.data
    },

    /*
     * 获取培训形式字典
     */
    async getTrainingFrom () {
      const result = await getAction(`${opDictNew.findByType}?type=rs_pxxs`)
      this.traningFrom = result.data
    },

    /*
     * 获取主办单位类别字典
     */
    async getOrganizerCategory () {
      const result = await getAction(`${opDictNew.findByType}?type=rs_he`)
      this.organizerCategory = result.data
    },

    /*
     * 获取主办单位性质字典
     */
    async getSponsorNature () {
      const result = await  getAction(`${opDictNew.findByType}?type=rs_bd`)
      this.sponsorNature = result.data
    },

    /*
     * 获取培训渠道字典
     */
    async getTraniningChannels () {
      const result = await getAction(`${opDictNew.findByType}?type=rs_spxqd`)
      this.traniningChannels = result.data
    },

    /**
     * 详情
     */
    detailRow (row) {
      if(!row){
        this.$message("请选择要编辑的数据！")
        return
      }
      this.ruleForm = JSON.parse(JSON.stringify(row))
      this.isUpdate = true
      this.dialogFormVisible = true
    },

    // 当前页改变
    currentChange (event) {
      this.pagination.pageNum = event
      this.getList()
    },

    /**
     * 清除form
     */
    clearForm () {
      this.ruleForm = {
        startTime: '',
        endTime: '',
        traniningCategory: '',
        traningDays: '',
        totalClassHours: '',
        traniningCourseName: '',
        learningContent: '',
        educationTraningNature: '',
        learningStyle: '',
        academicRecord: '',
        educationTraningResults: '',
        traningFrom: '',
        organizerCategory: '',
        organizer: '',
        sponsorNature: '',
        undertaker: '',
        investmentAmont: '',
        traniningChannels: ''
      }
    },

    handleClose () {},
    handleChange () {},
    rowClass ({ row, rowIndex }) {
      return 'background:rgba(248, 248, 249, 1);color:#000;'
    }
  }
}
</script>

<style scoped>

.table_tools {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
